<!-- 费用审核 系统级的，即一级路由标题栏-->
<template>
  <div>
    <a-card id="a">
      <!-- tab 切换日志 start -->
      <a-tabs @change="handleTab">
        <a-tab-pane :tab="list.desc" v-for="list in statusList" :key="list.value"> </a-tab-pane>
      </a-tabs>
      <!-- tab 切换日志  end -->
      <div>
        <s-table ref="table" size="default" :rowKey="record => record.id" bordered :columns="columns" :data="loadData"
          :scroll="{ x: 1200 }">
          <template slot="title">
            <a-descriptions :title="$t('all.autotext469')"></a-descriptions>
            <div class="table-page-search-wrapper">
              <a-form layout="inline">
                <a-row :gutter="48">
                  <a-col :xl="8" :lg="12" :md="24" :sm="24">
                    <a-form-item :label="$t('all.autotext1156')">
                      <a-input v-model="queryParam.applyNo" :placeholder="$t('all.autotext1371')" />
                    </a-form-item>
                  </a-col>
                  <a-col :xl="8" :lg="12" :md="24" :sm="24">
                    <a-form-item :label="$t('all.autotext1236')">
                      <a-select v-model="queryParam.type" :placeholder="$t('all.autotext1348')" default-value="0"
                        allowClear>
                        <a-select-option v-for="item in $const.SUBJECTANDREESA" :key="item.value" :value="item.value">
                          {{ item.desc }}
                        </a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <template v-if="advanced">
                    <a-col :xl="8" :lg="12" :md="24" :sm="24">
                      <a-form-item :label="$t('all.autotext1521')">
                        <a-input v-model="queryParam.createUserNo" :placeholder="$t('all.autotext1371')" />
                      </a-form-item>
                    </a-col>
                    <a-col :xl="8" :lg="12" :md="24" :sm="24">
                      <a-form-item :label="$t('all.autotext1251')">
                        <a-input v-model="queryParam.userNo" :placeholder="$t('all.autotext1371')" />
                      </a-form-item>
                    </a-col>
                    <a-col :xl="8" :lg="12" :md="24" :sm="24">
                      <a-form-model-item :label="$t('all.autotext758')" labelAlign="left">
                        <a-range-picker @change="handleSelectDate" v-model="queryDate" />
                      </a-form-model-item>
                    </a-col>
                    <a-col :xl="8" :lg="12" :md="24" :sm="24">
                      <a-form-model-item :label="$t('all.autotext992')" labelAlign="left">
                        <a-select v-model="queryParam.env" :placeholder="$t('all.autotext1348')" default-value="PRO"
                          style="width: 20%;margin-right: 8px;" allowClear>
                          <a-select-option value="1">PRO</a-select-option>
                          <a-select-option value="2">UAT</a-select-option>
                        </a-select>
                        <a-input v-model="queryParam.projectNo" :placeholder="$t('all.autotext1371')"
                          style="width: calc(80% - 8px);" />
                      </a-form-model-item>
                    </a-col>
                  </template>
                  <a-col :xl="8" :lg="12" :md="24" :sm="24">
                    <span class="table-page-search-submitButtons" :style="(advanced && { overflow: 'hidden' }) || {}">
                      <a-button type="primary" @click="searchTable">{{ $t('all.autotext30') }}</a-button>
                      <a-button style="margin-left: 8px" @click="reset">{{ $t('all.autotext340') }}</a-button>
                      <a-button style="margin-left: 8px" type="button" icon="download" @click="clickExport"
                        v-if="$auth('FEE_REVIEW.FEE_REVIEW_EXPORT')">{{ $t('all.autotext1014') }}</a-button>
                      <a @click="toggleAdvanced" style="margin-left: 8px">
                        {{ advanced ? $t('all.autotext760.1') : $t('all.autotext760.2') }}
                        <a-icon :type="advanced ? 'up' : 'down'" />
                      </a>
                    </span>
                  </a-col>
                </a-row>
              </a-form>
            </div>
          </template>
          <template slot="createTime" slot-scope="text, record">
            <span v-if="record.createTime">{{ record.createTime | moment() }}</span>
          </template>
          <template slot="totalAmount" slot-scope="text, record">
            <span>{{ record.totalAmount | formatAmount }}</span>
          </template>
          <template slot="type" slot-scope="text, record">
            {{ record.type == 1 ? $t('all.autotext1096') : $t('all.autotext446') }}
          </template>
          <template slot="projectNo" slot-scope="text, record">
            <a @click="switchToProject(record)">{{ record.projectNo }}</a>
          </template>
          <template slot="payTime" slot-scope="text, record">
            <span v-if="record.payTime">{{ record.payTime | moment() }}</span>
          </template>
          <template slot="status" slot-scope="text, record">
            {{ record.status | enumValueByKey($const.EXAMINE_TYPE) }}
          </template>
          <template slot="operation" slot-scope="text, record">
            <a @click="clickView(record)" v-if="$auth('FEE_REVIEW.FEE_REVIEW_DETAIL')">{{ $t('all.autotext568') }}</a>
          </template>
          <template slot="userNo" slot-scope="text, record">
            <span>{{ record.type == $const.SUBJECTANDREESA.DAISHENGPI.value ? record.researchDetailNo : record.ptsNo
            }}</span>
          </template>
        </s-table>
        <DetailView @refresh="$refs.table.refresh()" @closeCallback="closeCallback" @openPopup="openPopup"
          @payRecord="payRecord" @moveSuccess="moveSuccess" ref="detailView" :visible="visible" :costId="costId"
          :advancedPay="advancedPay" />
        <AuditFailure :visible="visibles" @uploadModalCancel="visibles = false" @uploadClickConfirm="uploadClickConfirm"
          :auditStatus="auditStatus" ref="AuditFailure" />
        <Approve v-model="oveVisibles" :applyNo="applyNo" :oldStatus="oldStatus" :auditStatus="auditStatus"
          @ok="approveOk" :max="preRecord.totalAmount" />
      </div>
    </a-card>
  </div>
</template>

<script>
import { auditList, switchAudit, costRecordPay, getCostExport, applyTax, preCheckForFinanceAudit } from '@/api/cost/audit'
import DetailView from '@/views/cost-auditing/detail.vue'
import AuditFailure from '@/views/cost-auditing/components/auditFailure'
import Approve from '@/views/cost-auditing/components/approve'
import { exportExcel } from '@/utils/util'
import { buildPaginationObj } from '@/components/Table'
import { FINANCE_STATUS } from '@/constants/common'

export default {
  components: {
    DetailView,
    AuditFailure,
    Approve
  },
  data() {
    return {
      statusIndex: 1,
      statusList: [],
      visible: false,
      visibles: false,
      oveVisibles: false,
      detailInfo: {},
      queryParam: {
        status: FINANCE_STATUS[0].value
      },
      advancedPay: 0,
      costId: 0,
      applyNo: '',
      oldStatus: '',
      queryDate: [],
      loadData: parameter => {
        if (this.$auth('FEE_REVIEW.FEE_REVIEW_LIST')) {
          return auditList(Object.assign(parameter, this.queryParam))
            .then(res => {
              this.pageSize = res.totalCount
              return res
            })
            .catch(() => { })
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      advanced: false,
      thisStatus: '',
      columns: [
        {
          title: this.$t('all.autotext1156'),
          key: 'applyNo',
          sorter: true,
          dataIndex: 'applyNo'
        },
        {
          title: this.$t('all.autotext244'),
          key: 'createTime',
          sorter: true,
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: this.$t('all.autotext229'),
          key: 'type',
          sorter: true,
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: this.$t('all.autotext1521'),
          dataIndex: 'applyAccount',
          customRender: (text, record) => {
            return `${record.applyRole} - ${record.applyAccount}`
          }
        },
        {
          title: this.$t('all.autotext597'),
          dataIndex: 'receiverAccount',
          customRender: (text, record) => {
            return `${record.receiverRole} - ${record.receiverAccount}`
          }
        },
        {
          title: this.$t('all.autotext992'),
          key: 'projectNo',
          sorter: true,
          dataIndex: 'projectNo',
          scopedSlots: { customRender: 'projectNo' }
        },
        {
          title: this.$t('all.autotext867'),
          key: 'totalAmount',
          sorter: true,
          dataIndex: 'totalAmount',
          scopedSlots: { customRender: 'totalAmount' }
        },
        {
          title: this.$t('all.autotext82'),
          key: 'payTime',
          sorter: true,
          dataIndex: 'payTime',
          scopedSlots: { customRender: 'payTime' }
        },
        {
          title: this.$t('all.autotext196'),
          key: 'payNo',
          sorter: true,
          dataIndex: 'payNo',
          scopedSlots: { customRender: 'payNo' }
        },
        {
          title: this.$t('all.autotext1466'),
          key: 'status',
          sorter: true,
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },

        {
          title: this.$t('all.autotext187'),
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      pageSize: null,
      auditStatus: {}, // 审核弹窗审核状态
      preRecord: {} // 当前查看对象
    }
  },
  mounted() {
    let roles = this.$store.getters.roles && this.$store.getters.roles.length ? this.$store.getters.roles :  [{}]
    // 财务显示待完税，其他不显示
    let arr = roles[0].code === 'SYS_FINANCE' ? FINANCE_STATUS : FINANCE_STATUS.filter(item => item.value !== 41)
    // 财务和项目不显示审核结束
    this.statusList = roles[0].code === 'PROJECT_ADMIN' ||   roles[0].code === 'SYS_FINANCE' ? arr.filter(item => item.value !== 70) : arr

  },
  methods: {
    approveOk() {
      this.visibles = false
      this.visible = false
      this.$refs.table.refresh()
    },
    // 用于切换tab状态的
    handleTab(key) {
      this.statusIndex = key
      this.queryParam.status = key
      this.$refs.table.refresh(true)
    },
    clickExport() {
      // const exportParams = { proId: 393, status: 30 }
      getCostExport({
        ...this.queryParam,
        pageSize: this.pageSize
      }).then(res => {
        exportExcel(this.$t('all.autotext469'), res)
      })
    },
    // 点击展开 详细搜索信息
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    // 点击重置
    reset() {
      if (this.queryParam.status) {
        this.queryParam = {
          status: this.queryParam.status
        }
      } else {
        this.queryParam = {}
      }
      this.queryDate = []
      this.$refs.table.refresh(true)
    },
    // 点击项目id跳转到项目详情
    switchToProject(record) {
      const { proId } = record
      const project = {
        id: proId
      }
      this.$store.commit('UPDATE_PROJECT', project)
      this.$router.push({ name: 'Responsible', query: { id: record.proId } })
      // this.$router.push({ name: 'Responsible', query: { id: record.proId } })
    },
    // 点击查看
    clickView(record) {
      console.log(this.visible)
      this.preRecord = record
      this.applyNo = record.applyNo
      this.oldStatus = record.status
      this.costId = record.id
      this.thisStatus = record.status
      this.advancedPay = record.advancedPay
      this.visible = true
    },
    // 处理发起日期选择框改变时产生的回调
    handleSelectDate(date, dateString) {
      this.queryDate = date
      this.queryParam.applyStartTime = dateString[0]
      this.queryParam.applyEndTime = dateString[1]
    },
    searchTable() {
      this.$refs.table.refresh(true)
    },
    // 弹窗关闭回调
    closeCallback() {
      this.visible = false
    },
    // 审核弹窗关闭回调
    uploadModalCancel() {
      this.visibles = false
      this.oveVisibles = false
    },
    // 审核弹窗确认回调
    uploadClickConfirm(value) {
      const status = value.status === true ? 1 : -1
      this.$refs.AuditFailure.confirmLoading = true
      switchAudit({ id: value.id, status: status, applyNo: this.applyNo, oldStatus: this.oldStatus, refuseReason: value.refuseReason, comment: value.comment, auditArray: value.auditArray.length ? JSON.stringify(value.auditArray) : undefined })
        .then(res => {
          this.$refs.AuditFailure.confirmLoading = false
          this.$refs.AuditFailure.form = {}
          this.$message.success(this.$t('all.autotext470'))
          this.uploadModalCancel()
          this.closeCallback()
          this.$refs.table.refresh()
          // FIX:(LEO) 取消自动报税
          // const isSubject = value.status && value.type && value.type === this.$const.SUBJECTANDREESA.DAIWANSHUI.value
          // if (isSubject) {
          //   this.subjectsAutoTaxed(value.id)
          // }
        })
        .catch(() => {
          this.$refs.AuditFailure.confirmLoading = false
        })
    },
    // 受试者自动完税
    subjectsAutoTaxed(id) {
      const taxedRequestParams = {
        applyNo: this.applyNo,
        oldStatus: 41, // 后端确认完税状态参数 41
        id,
        personalTax: 0
      }
      applyTax(taxedRequestParams)
    },
    // 打开审核弹窗
    async openPopup(value) {
      if (value.status === 1) {
        this.auditStatus = value
        this.oveVisibles = true
        return
      }
      if (value.status === true && this.$store.getters.roles[0]?.code === 'SYS_FINANCE') {
        const check = await preCheckForFinanceAudit({ feeApplyId: value.id })
        if (check.flag) {
          const that = this
          this.$confirm({
            title: this.$t('all.autotext730'),
            content: (h) => {
              return h('div', check.message.map(node => h('p', node)))
            },
            onOk() {
              that.auditStatus = value
              that.visibles = true
            }
          })
        } else {
          this.auditStatus = value
          this.visibles = true
        }
        return
      }
      this.auditStatus = value
      this.visibles = true
    },
    payRecord() {
      this.$refs.detailView.payLoading = true
      costRecordPay({ id: this.costId, applyNo: this.applyNo }).then(res => {
        this.$refs.detailView.payLoading = false
        this.$message.success(this.$t('all.autotext470'))
        this.closeCallback()
        this.uploadModalCancel()
        this.$refs.table.refresh()
      }).catch(_ => {
        this.$refs.detailView.payLoading = false
      })
    },
    moveSuccess() {
      this.closeCallback()
      this.$refs.table.refresh()
    }
  }
}
</script>

